package com.ruoyi.SuveryInterface.CommercialSuvery;


import com.alibaba.fastjson2.JSON;
import com.ruoyi.SuveryInterface.Imp.domain.SysCommercial;
import com.ruoyi.SuveryInterface.Imp.domain.SysCredit;
import com.ruoyi.SuveryInterface.Imp.domain.SysMessage;
import com.ruoyi.SuveryInterface.Imp.mapper.*;
import com.ruoyi.SuveryInterface.SuveryUtils.ClientRequest;
import com.ruoyi.SuveryInterface.SuveryUtils.Constants;
import com.ruoyi.SuveryInterface.SuveryUtils.CustomerKeys;
import com.ruoyi.SuveryInterface.SuveryUtils.util.HttpClientUtils;
import com.ruoyi.SuveryInterface.SuveryUtils.util.RsaSignature;
import com.ruoyi.SuveryInterface.SuveryUtils.util.SerialNumberUtil;
import com.ruoyi.SuveryInterface.SuveryUtils.util.ThreeDesUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

// 银行卡二要素 卡号 手机
public class CommercialNameAndCard {

	private SysCommercialMapper commercialMapper;

	private SysLegalInfosMapper legalInfosMapper;

	private SysShareholderInfosMapper shareholderInfosMapper;

	private SysManagerInfosMapper managerInfosMapper;

	private SysPunishedsMapper punishedsMapper;

	private SysPunishBreaksMapper punishBreaksMapper;

	private SysAdminPenaltyMapper adminPenaltyMapper;

	public CommercialNameAndCard(SysCommercialMapper commercialMapper, SysLegalInfosMapper legalInfosMapper, SysShareholderInfosMapper shareholderInfosMapper, SysManagerInfosMapper managerInfosMapper, SysPunishedsMapper punishedsMapper, SysPunishBreaksMapper punishBreaksMapper, SysAdminPenaltyMapper adminPenaltyMapper) {
		this.commercialMapper = commercialMapper;
		this.legalInfosMapper = legalInfosMapper;
		this.shareholderInfosMapper = shareholderInfosMapper;
		this.managerInfosMapper = managerInfosMapper;
		this.punishedsMapper = punishedsMapper;
		this.punishBreaksMapper = punishBreaksMapper;
		this.adminPenaltyMapper = adminPenaltyMapper;
	}

	public SysCommercialMapper getCommercialMapper() {
		return commercialMapper;
	}

	public void setCommercialMapper(SysCommercialMapper commercialMapper) {
		this.commercialMapper = commercialMapper;
	}

	public SysLegalInfosMapper getLegalInfosMapper() {
		return legalInfosMapper;
	}

	public void setLegalInfosMapper(SysLegalInfosMapper legalInfosMapper) {
		this.legalInfosMapper = legalInfosMapper;
	}

	public SysShareholderInfosMapper getShareholderInfosMapper() {
		return shareholderInfosMapper;
	}

	public void setShareholderInfosMapper(SysShareholderInfosMapper shareholderInfosMapper) {
		this.shareholderInfosMapper = shareholderInfosMapper;
	}

	public SysManagerInfosMapper getManagerInfosMapper() {
		return managerInfosMapper;
	}

	public void setManagerInfosMapper(SysManagerInfosMapper managerInfosMapper) {
		this.managerInfosMapper = managerInfosMapper;
	}

	public SysPunishedsMapper getPunishedsMapper() {
		return punishedsMapper;
	}

	public void setPunishedsMapper(SysPunishedsMapper punishedsMapper) {
		this.punishedsMapper = punishedsMapper;
	}

	public SysPunishBreaksMapper getPunishBreaksMapper() {
		return punishBreaksMapper;
	}

	public void setPunishBreaksMapper(SysPunishBreaksMapper punishBreaksMapper) {
		this.punishBreaksMapper = punishBreaksMapper;
	}

	public SysAdminPenaltyMapper getAdminPenaltyMapper() {
		return adminPenaltyMapper;
	}

	public void setAdminPenaltyMapper(SysAdminPenaltyMapper adminPenaltyMapper) {
		this.adminPenaltyMapper = adminPenaltyMapper;
	}

	private static String baseUrl ="https://api.jizhengyun.com/v1.0/realname/";

	//名字和身份证
	public SysCommercial QueryCommercial(String name , String cert_no,Long orderId) throws Exception {



//		String acct_no = "6222030502005030526";
//		String phone = "13643669790";
//		String name = "吕宇宏";
//		String cert_no = "141124200308110076";
		if (true) {
			throw new Exception();
		}

		String cert_type = "";
		// 订单号
		String out_trade_no = SerialNumberUtil.createBillNo();
		String tran_time = "2024-07-01 12:01:30";
		String verify_type = "09322";
		//测试商户号
		String cutomer_code = CustomerKeys.customer_code;
		String url = baseUrl + cutomer_code;
		// 3des密钥
		String des_key = CustomerKeys.des_key;
		//RSA私钥
		String rsa_key = CustomerKeys.rsa_key;
		ClientRequest molinkRequest = new ClientRequest();
		molinkRequest.setOut_trade_no(out_trade_no);
		molinkRequest.setTran_time(tran_time);
		molinkRequest.setVerify_type(verify_type);
		molinkRequest.setCustomer_code(cutomer_code);
//		molinkRequest.setAcct_no(acct_no);
//		molinkRequest.setPhone(phone);

		molinkRequest.setName(name);
		molinkRequest.setCert_no(cert_no);

		StringBuilder builder = new StringBuilder();
		builder.append(Constants.out_trade_no.toUpperCase() + "=" + out_trade_no);
		builder.append("&" + Constants.tran_time.toUpperCase() + "=" + tran_time);
		builder.append("&" + Constants.verify_type.toUpperCase() + "=" + verify_type);
//		builder.append("&" + Constants.acct_no.toUpperCase() + "=" + acct_no);
//		builder.append("&" + Constants.phone.toUpperCase() + "=" + phone);
		builder.append("&" + Constants.name.toUpperCase() + "=" + name);
		builder.append("&" + Constants.cert_no.toUpperCase() + "=" + cert_no);


		System.out.println("加签信息:"+builder.toString());
		String sign = RsaSignature.rsaSign(builder.toString(), rsa_key, Constants.CHARSET_UTF8);
		molinkRequest.setSign(sign);

		String json = JSON.toJSONString(molinkRequest);
		System.out.println("发送报文信息:"+json.toString());
		byte[] keybyte = des_key.getBytes();
		byte[] requsest = ThreeDesUtil.encryptMode(keybyte, json.getBytes());
		String code = HttpClientUtils.ysPost(url, ThreeDesUtil.byte2Hex(requsest));

		SysCommercial commercialEntity = getCommercialEntity(code);
		commercialEntity.setOrderId(orderId);
		insertCommercial(commercialEntity);


		// 验签流程：
		// 1、获取验签参数
		// 2、拼接验签字符串
		// 3、使用验签方法进行验签

		try {
			JSONObject jsonObject = JSONObject.fromObject(code);
			String signContent = jsonObject.getString("sign");
			String CODE = jsonObject.getString("code");
			String MESSAGE = jsonObject.getString("message");
			String OUT_TRADE_NO = jsonObject.getString("out_trade_no");
			String TRAN_AMT = jsonObject.getString("tran_amt");
			String TRAN_TIME = jsonObject.getString("tran_time");

			StringBuilder signbuilder = new StringBuilder();
			signbuilder.append(Constants.code.toUpperCase() + "=" + CODE);
			signbuilder.append("&" + Constants.message.toUpperCase() + "=" + MESSAGE);
			signbuilder.append("&" + Constants.out_trade_no.toUpperCase() + "=" + OUT_TRADE_NO);
			signbuilder.append("&" + Constants.tran_amt.toUpperCase() + "=" + TRAN_AMT);
			signbuilder.append("&" + Constants.tran_time.toUpperCase() + "=" + TRAN_TIME);

			// 系统公钥
			String key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9TbGYWcBGAWmB2f6uzuZQeZ8algiHz63OXlumUAX0Dlyh+15RQ3VKs//bsgx9RUaSzyae1vmXtKGlYzy/jk8dqljTPolyJZ6rrpJ9F/kzZpHHYYmLAQX+LVGSNYoxormAvpTg2sce/pJWyr6fiHvNyM8YXQnxQwDkO4Ert3sELQIDAQAB";
			boolean signResult = RsaSignature.rsaCheckContent(signbuilder.toString(), signContent, key,
					Constants.CHARSET_UTF8);
			if (signResult) {
				System.out.println("验签成功");
			} else {
				System.out.println("验签失败");
			}
		} catch (Exception e) {
		}

		return commercialEntity;
	}

	private static String changeCharSet(String str, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			// 用默认字符编码解码字符串。
			byte[] bs = str.getBytes();
			// 用新的字符编码生成字符串
			return new String(bs, newCharset);
		}
		return str;
	}

	private SysCommercial getCommercialEntity(String code) {
		SysCredit sysCredit = com.alibaba.fastjson.JSONObject.parseObject(code, SysCredit.class);

		if (sysCredit.getCode().equals("1009")) {
			throw new ServiceException("参数错误");
		}
		else if (!sysCredit.getCode().equals("0000") && !sysCredit.getCode().equals("1404")) {
			throw new RuntimeException();
		}
		SysMessage sysMessage = com.alibaba.fastjson.JSONObject.parseObject(sysCredit.getMessage(), SysMessage.class);
		String data = sysMessage.getData();
		SysCommercial sysCommercial = new SysCommercial();
		if (!StringUtils.isEmpty(data)){
			com.alibaba.fastjson.JSONObject SysCommercials = com.alibaba.fastjson.JSONObject.parseObject(sysMessage.getData());
			List<com.alibaba.fastjson.JSONObject> legalInfos = (List<com.alibaba.fastjson.JSONObject>) SysCommercials.get("legalInfos");
			List<com.alibaba.fastjson.JSONObject> shareholderInfos = ( List<com.alibaba.fastjson.JSONObject>)SysCommercials.get("shareholderInfos");
			List<com.alibaba.fastjson.JSONObject> managerInfos =(List<com.alibaba.fastjson.JSONObject>) SysCommercials.get("managerInfos");
			List<com.alibaba.fastjson.JSONObject> punisheds = ( List<com.alibaba.fastjson.JSONObject>)SysCommercials.get("punisheds");
			List<com.alibaba.fastjson.JSONObject> punishBreaks =(List<com.alibaba.fastjson.JSONObject> ) SysCommercials.get("punishBreaks");
			List<com.alibaba.fastjson.JSONObject> adminPenalty =(List<com.alibaba.fastjson.JSONObject>) SysCommercials.get("adminPenalty");

			sysCommercial.setLegalInfos(legalInfos);
			sysCommercial.setShareholderInfos(shareholderInfos);
			sysCommercial.setManagerInfos(managerInfos);
			sysCommercial.setPunisheds(punisheds);
			sysCommercial.setPunishBreaks(punishBreaks);
			sysCommercial.setAdminPenalties(adminPenalty);
			//处理legalinfos

		}




//        SysDegrees sysDegrees = new SysDegrees();

		BeanUtils.copyProperties(sysCredit,sysCommercial);
		BeanUtils.copyProperties(sysMessage,sysCommercial);

		sysCommercial.setOutTradeNo(sysCredit.getOut_trade_no());
		sysCommercial.setTranAmt(sysCredit.getTran_amt());
		sysCommercial.setTranTime(sysCredit.getTran_time());
		sysCommercial.setCreateTime(new Date());
//        return sysEducation;
		return sysCommercial;
	}

	private void insertCommercial(SysCommercial commercialEntity) {
		//执行插入操作：
		//1.插入到工商主表中数据
		SysCommercial sysCommercial = new SysCommercial();
		BeanUtils.copyProperties(commercialEntity,sysCommercial);

		commercialMapper.insertSysCommercial(sysCommercial);
		//2.插入到legalInfos
		List<com.alibaba.fastjson.JSONObject> legalInfos = commercialEntity.getLegalInfos();
		if (!CollectionUtils.isEmpty(legalInfos) ) {
			for (com.alibaba.fastjson.JSONObject legalInfo : legalInfos) {
				legalInfo.put("sysCommercialId",sysCommercial.getId());
			}
			legalInfosMapper.insertSysLegal(legalInfos);
		}


		//3.插入到shareholderInfos
		List<com.alibaba.fastjson.JSONObject> shareholderInfos = commercialEntity.getShareholderInfos();
		if (!CollectionUtils.isEmpty(shareholderInfos)) {
			for (com.alibaba.fastjson.JSONObject shareholderInfo : shareholderInfos) {
				shareholderInfo.put("sysCommercialId",sysCommercial.getId());
			}
			shareholderInfosMapper.insertSysShareholder(shareholderInfos);
		}

		//4.插入到managerInfos
		List<com.alibaba.fastjson.JSONObject> managerInfos = commercialEntity.getManagerInfos();
		if (!CollectionUtils.isEmpty(managerInfos) ) {
			for (com.alibaba.fastjson.JSONObject managerInfo : managerInfos) {
				managerInfo.put("sysCommercialId",sysCommercial.getId());
			}
			managerInfosMapper.insertSysManager(managerInfos);
		}

		//5.插入到punisheds
		List<com.alibaba.fastjson.JSONObject> punisheds = commercialEntity.getPunisheds();
		if (!CollectionUtils.isEmpty(punisheds) ) {
			for (com.alibaba.fastjson.JSONObject punished : punisheds) {
				punished.put("sysCommercialId",sysCommercial.getId());
			}
			punishedsMapper.insertSysPunisheds(punisheds);
		}

		//6.插入到punishBreaks
		List<com.alibaba.fastjson.JSONObject> punishBreaks = commercialEntity.getPunishBreaks();
		if (!CollectionUtils.isEmpty(punishBreaks)) {
			for (com.alibaba.fastjson.JSONObject punishBreak : punishBreaks) {
				punishBreak.put("sysCommercialId",sysCommercial.getId());
			}
			punishBreaksMapper.insertSysPunishBreaks(punishBreaks);
		}

		//7.插入到adminPenalty
		List<com.alibaba.fastjson.JSONObject> adminPenalties = commercialEntity.getAdminPenalties();
		if (!CollectionUtils.isEmpty(adminPenalties)) {
			for (com.alibaba.fastjson.JSONObject adminPenalty : adminPenalties) {
				adminPenalty.put("sysCommercialId",sysCommercial.getId());
			}
			adminPenaltyMapper.insertSysAdminPenalty(adminPenalties);

		}
	}


}
